package com.example.blenderandroid;

import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

//TODO use action bar to search for a device

public class SelectPairedDeviceActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_paired);

		ListView pairedDevicesView = (ListView) findViewById(R.id.paired_devices_view);
		ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
		pairedDevicesView.setAdapter(listAdapter);
		
		// add all paired bluetooth devices to the ListView
    	BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    	Set<BluetoothDevice> pairedDevicesSet = bluetoothAdapter.getBondedDevices();
    	final BluetoothDevice[] pairedDevices = new BluetoothDevice[pairedDevicesSet.size()];
		int i = 0;
		for (BluetoothDevice device : pairedDevicesSet) {
			pairedDevices[i] = device;
			listAdapter.add(device.getName() + "\n" + device.getAddress());
			++i;
		}
		
		pairedDevicesView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent connectBtIntent = new Intent(SelectPairedDeviceActivity.this, ConnectBtActivity.class);
				
				// attach the address of the chosen bluetooth device to the intent
				BluetoothDevice selectedDevice = pairedDevices[position];
				connectBtIntent.putExtra(ConnectBtActivity.BT_ADDRESS, selectedDevice.getAddress());
				
				SelectPairedDeviceActivity.this.startActivity(connectBtIntent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.select_paired, menu);
		return true;
	}
}
